package com.mlz.filter;

import com.alibaba.fastjson.JSONObject;
import com.mlz.pojo.Result;
import com.mlz.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")//拦截所有的请求
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //强制类型转换成HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求url
        String url = request.getRequestURL().toString();
        log.info("请求路径:{}",url);

        //2.判断请求url中是否包含login,如果包含,说明是登录操作, 直接放行
        if (url.contains("/login")) {
            //放行请求
            chain.doFilter(request, response);
            return;//结束当前方法的执行
        }

        //3.获取请求头中的令牌
        String token = request.getHeader("token");
        log.info("从请求头中获取令牌:{}",token);

        //4.判断令牌是否存在,如果不存在,返回错误结果(未登录)
        if (!StringUtils.hasLength(token)) {
            Result notLogin = Result.error("NOT_LOGIN");

            //把Result对象转换成JSON格式的字符串
            String json = JSONObject.toJSONString(notLogin);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

            return;
        }

        //5.解析token,如果解析失败,返回错误结果(未登录)
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            Result notLogin = Result.error("NOT_LOGIN");

            //把Result对象转换成JSON格式的字符串
            String json = JSONObject.toJSONString(notLogin);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

            return;
        }

        //6.放行
        chain.doFilter(request, response);
    }
}
